/**
 * Copyright (C) @2014 Webank Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.webank.framework.seq.model;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

public class SequenceRange implements Comparable<SequenceRange> {
	private final long min;
	private final long max;
	private final AtomicLong value;
	private volatile boolean over = false;
	/**
	 * seq记录生成时间
	 */
	private volatile Date modifiedTime;

	public Date getModifiedTime() {
		return this.modifiedTime;
	}

	public void setModifiedTime(Date modifiedTime) {
		this.modifiedTime = modifiedTime;
	}

	public SequenceRange(long min, long max, Date modifiedTime) {
		this.min = min;
		this.max = max;
		this.value = new AtomicLong(min);
		this.modifiedTime = modifiedTime;
	}

	public long incrementAndGet() {
		long currentValue = this.value.incrementAndGet();
		if (currentValue > this.max) {
			this.over = true;
			return -1L;
		}
		return currentValue;
	}

	public boolean isOver() {
		return this.over;
	}

	public void setOver(boolean over) {
		this.over = over;
	}

	public long getMin() {
		return this.min;
	}

	public long getMax() {
		return this.max;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(SequenceRange seq) {
		if (seq == null)
			return 1;

		if (this.getMax() < seq.getMax() && this.getMin() < seq.getMin())
			return -1;
		else if (this.getMax() == seq.getMax() && this.getMin() < seq.getMin())
			return -1;
		else if (this.getMax() < seq.getMax() && this.getMin() == seq.getMin())
			return -1;
		else if (this.getMax() == seq.getMax() && this.getMin() == seq.getMin())
			return 0;
		else if (this.getMax() == seq.getMax() && this.getMin() > seq.getMin())
			return 1;
		else if (this.getMax() > seq.getMax() && this.getMin() == seq.getMin())
			return 1;
		else if (this.getMax() > seq.getMax() && this.getMin() > seq.getMin())
			return 1;
		else if (this.getMax() == seq.getMax() && this.getMin() > seq.getMin())
			return 1;
		else
			return -1;

	}
}
